package control;

import java.io.*;



/**
 * 
 * @author Thomas
 * 
 * This class handles all the saving and loading called by the save and load dialogs
 */
public class SaveHandler 
{
	private ObjectOutputStream oos;
	private ObjectInputStream ois;
	
	public SaveHandler() 
	{
		
	}
	
	/**
	 * This method gets the current Instance of the GameControl 
	 * and extracts the CardControl, FieldsControl, and PlayerControl
	 * and saves them via a ObjectOutputstream into a file specified in the save dialog.
	 * @param name The name the User specifies to save the file.
	 */
	public void save(String name) 
	{
		File saveDir = new File("saves");
		System.out.println("Checking for directory");
		if(saveDir.exists())
			System.out.println("Found save Directory");
		else
		{
			if(saveDir.mkdir())
				System.out.println("Creating saves directory");
			else
				System.out.println("Could not create saves directory");
		}
		
		System.out.println("Saving..");
		
		GameControl gc = GameControl.getControlInstance();
		try
		{
			oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("saves/" + name + ".dat")));
			oos.writeObject(gc.getFieldsControl());
			oos.writeObject(gc.getCardControl());
			oos.writeObject(gc.getPlayerControl());
			oos.writeObject(gc.getGameTime());
			oos.flush();
			oos.close();
		}
		catch(Exception exc){exc.printStackTrace();}//System.err.println(exc.getMessage());}
			
	}
	
	/**
	 * This method reads from the save file specified in the load dialog.
	 * it then reads the three control classes (player, card, fields), in
	 * the same order as in the save() method (!).
	 * From there, the current state and the board to continue the game can 
	 * be reconstructed.
	 * 
	 * @param name The file name from which the game should be loaded.
	 * @return An array containing the FieldsControl, the CardsControl and the PlayerControl
	 */
	public Object[] load(String name) 
	{
		System.out.println("Loading..");
		Object[] controls = new Object[4];
		
		try
		{
			ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("saves/" + name + ".dat")));
			controls[0] = ois.readObject();
			controls[1] = ois.readObject();
			controls[2] = ois.readObject();
			controls[3] = ois.readObject();
			
			ois.close();
		}
		catch(Exception exc) {System.err.println(exc.getMessage());}
		
		return controls;
	}

}
